<template>
  <el-container class="app_container flex">
    <Aside @handleNodeClick="handleNodeClick" />
    <el-main class="app_main flex">
      <Breadcrumb :title="pageTitle" />
      <div class="app_content">
        <el-form ref="searchForm" :model="searchMap">
          <el-row class="flex serach_item">
            <el-button v-for="(item, index) in this.deviceClassList" :key="item.deviceTypeId + index" type="primary" :class="setDeviceClassifyActive(item.deviceTypeId)" @click="getDeviceType(item)">{{ item.deviceTypeName }}</el-button>
          </el-row>
          <el-row class="flex serach_item">
            <span class="label-tip">设备类型：</span>
            <el-button v-for="(item, index) in this.deviceTypeList" :key="item.deviceTypeId + index" type="primary" :class="setDeviceTypeActive(item.deviceTypeId)" @click="getList(item)">{{ item.deviceTypeName }}（{{ item.deviceNum }}）</el-button>
          </el-row>
          <div class="serach_wrapper flex-space-between el-form--inline">
            <div class="search flex">
              <el-form-item prop="deviceName" size="small">
                <el-input v-model="searchMap.deviceName" placeholder="请输入设备名称"></el-input>
              </el-form-item>
              <el-form-item prop="enableStatus" size="small">
                <el-select v-model="searchMap.enableStatus" placeholder="是否启用" clearable>
                  <el-option v-for="dict in dict.type.device_enable_status" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item prop="deviceStatus" size="small">
                <el-select v-model="searchMap.deviceStatus" placeholder="设备状态" clearable>
                  <el-option v-for="dict in dict.type.device_status" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>

              <el-form-item class="flex">
                <el-button @click="handleSearch()" class="btn_primary">查询</el-button>
                <el-button @click="handleReset()" class="btn_cancel">重置</el-button>
              </el-form-item>
            </div>
            <div class="edit">
              <el-form-item class="flex">
                <el-button @click="dialogVisibleBatchExport = true" class="btn_primary" icon="el-icon-plus"> 批量导入 </el-button>
                <el-button @click="handleAdd" class="btn_primary" icon="el-icon-plus"> 新增 </el-button>
                <el-button @click="handleDelete" class="btn_primary" icon="el-icon-delete"> 删除 </el-button>
              </el-form-item>
            </div>
          </div>
        </el-form>
        <el-table :data="dataList" v-loading="loading" stripe class="per_table" @selection-change="handleSelectionChange" style="width: 100%" :height="winTableH">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="deviceTypeName" label="设备类型"></el-table-column>
          <el-table-column prop="deviceStatus" label="设备状态">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.device_status" :value="scope.row.deviceStatus" />
            </template>
          </el-table-column>
          <el-table-column prop="deviceCode" label="设备编号"></el-table-column>
          <el-table-column prop="deviceName" label="设备名称"></el-table-column>
          <el-table-column prop="installPosition" label="设备位置"></el-table-column>
          <el-table-column prop="remark" label="备注"></el-table-column>
          <el-table-column key="enableStatus" label="是否启用">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.device_enable_status" :value="scope.row.enableStatus" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="320">
            <template slot-scope="scope">
              <div class="">
                <span type="text" class="tag_primary" size="small" @click="handleAddFactors(scope.row)">新增设备因子</span>
                <span type="text" class="tag_primary" size="small" @click="handleEdit(scope.row)">编辑</span>
                <!-- <span type="text" class="tag_warning" size="small" @click="handleDelete(scope.row)">删除</span> -->
                <span v-if="scope.row.cameraFlag == 1" type="text" class="tag_danger" size="small" @click="handleConnect(scope.row)">关联设备</span>
                <!-- <span type="text" class="tag_danger" size="small" @click="handleConnect(scope.row)">关联设备</span> -->
                <span type="text" class="tag_warning" size="small" @click="handleRepair(scope.row)">一键报修</span>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <Pagination v-show="total > 0" :total="total" :page.sync="searchMap.pageNum" :limit.sync="searchMap.pageSize" @change="getList"></Pagination>
        <!-- 分页over -->

      </div>

      <!-- 弹窗 设备 新增/编辑 -->
      <!-- <el-dialog title="告警处理" class="large_dialog" :visible.sync="dialogVisible" top="10px">
        <Management :details="alarmDetails" @repace="getList" ></Management>
      </el-dialog> -->
      <!-- 弹窗 设备 新增/编辑 over -->

      <!-- 弹窗 设备 新增/编辑 -->
      <ManagementForm ref="addDeviceForm" :formData="formData" :tabActive="tabActive" :deviceClassList="deviceClassList" :dictMap="dict" :titleIndex="titleIndex" :dialogVisible="dialogVisible" @cancel="cancel" @getList="getData" @setTabActive="setTabActive"></ManagementForm>
      <!-- <ManagementForm :formData="formData" :tabActive="tabActive" :dictMap="dict" :titleIndex="titleIndex" :dialogVisible="dialogVisible" @cancel="cancel" @setTabActive="setTabActive"></ManagementForm> -->
      <!-- 弹窗 设备 新增/编辑 over -->

      <!-- 弹窗 设备因子 新增/编辑 -->
      <FactorsForm :formData="formFactorsData" :dictMap="dict" :titleIndex="titleIndexFactors" :dialogVisible="dialogVisibleFactors" @cancel="cancelFactors" @getList="getList"></FactorsForm>
      <!-- 弹窗 设备因子 新增/编辑 over -->

      <!-- 弹窗 详情 -->
      <!-- <OperationLogDetail :descData="descData" :dictMap="dict" :dialogVisible="dialogVisibleDetail" @cancel="cancelDetail"></OperationLogDetail> -->
      <!-- 弹窗 详情 over -->

      <!-- 弹窗 关联设备 -->
      <DeviceConnect ref="deviceConnect" :formData="formData" :dialogVisible="dialogVisibleDeviceConnect" @cancel="cancelDeviceConnect"></DeviceConnect>
      <!-- 弹窗 关联设备 over -->

      <!-- 批量导入 -->
      <ExportList :dialogVisible="dialogVisibleBatchExport" @cancel="dialogVisibleBatchExport = false"></ExportList>
      <!-- 批量导入 over -->

      <!-- 弹窗 一键报修 -->
      <DeviceRepair ref="deviceRepair" :dictMap="dict" :formData="formData" :dialogVisible="dialogRepair" @cancel="cancelRepair"></DeviceRepair>
      <!-- 弹窗 一键报修 over -->

    </el-main>
  </el-container>
</template>

<script>
import { listDeviceData, delDeviceData, statDeviceTypeUnderDeviceNum } from '@/api/system/device/management';
import { listDeviceTypesData } from '@/api/system/device/types';
import Aside from '@/components/Aside';
import Breadcrumb from '@/components/Breadcrumb';
import ManagementForm from '@/views/system/device/ManagementForm';
import FactorsForm from '@/views/system/device/FactorsForm';
import DeviceConnect from '@/views/system/device/DeviceConnect';
import ExportList from '@/views/system/device/ExportList'
import DeviceRepair from '@/views/system/device/DeviceRepair'
import { EventBus } from '@/utils/eventbus';
import { getProjectPointControlList } from '@/api';

export default {
  name: 'DeviceManagement',
  dicts: ['device_status', 'device_enable_status', 'device_alarm_notice_status', 'device_control_status', 'device_indoor', 'device_communicate_type', 'device_problem'],
  data() {
    return {
      // 新增或编辑弹窗的默认选中tab
      tabActive: 0,
      // 遮罩层
      loading: false,
      // 设备系统分类列表
      deviceClassList: [],
      // 设备类型列表
      deviceTypeList: [],
      // 搜索条件
      searchMap: {
        pageNum: 1,
        pageSize: 10,
        deptId: '',
        // deviceClassifyId: '1776532180145684481',
        deviceClassifyId: '',
        deviceName: '',
        deviceStatus: '',
        deviceTypeId: '',
        deviceTypeKey: '',
        enableStatus: '',
        projectPointName: "",
        projectPointId: ""
      },
      // 总条数
      total: 0,
      // 告警列表
      alarmList: [],
      // 数据列表
      dataList: [],
      // 表单字段数据
      formData: {
        projectPointId:'',
        projectPointName: '',
        positionX: 0,
        positionY: 0
      },
      // 表单字段数据-设备因子
      formFactorsData: {
        deviceId: '',
        alarmLowerLimit: '',
        alarmUpperLimit: '',
        factorCode: '',
        factorName: '',
        lowerLimit: '',
        upperLimit: '',
        unit: '',
        sort: 0,
        remark: ''
      },
      // 详情数据
      descData: {},
      // 弹窗-新增，编辑头文字
      titleIndex: 0,
      // 弹窗-新增设备因子，编辑头文字
      titleIndexFactors: 0,
      // 弹窗-新增/编辑-显示隐藏
      dialogVisible: false,
      // 弹窗-关联设备-显示隐藏
      dialogVisibleDeviceConnect: false,
      // 弹窗-详情-显示隐藏
      // dialogVisibleDetail: false,
      // 弹窗-设备因子-显示隐藏
      dialogVisibleFactors: false,
      // 批量导入弹框
      dialogVisibleBatchExport: false,
      // 一键报修弹框
      dialogRepair: false,
      // 项目点列表
      projectPoint: undefined,
      // 设备类型统计总数
      sum: 0,
      alarmDetails: {},
      // 项目点图片列表
      ProjectPointPicList: []

    };
  },
  created() {
    EventBus.$on('currentTree', data => {
      this.searchMap.deptId = data.id
      this.searchMap.projectPointName = data.projectPointName
      this.searchMap.projectPointId = data.projectPointId

      this.getListDeviceTypesData()
    })

  },
  computed: {
    pageTitle() {
      return '设备管理';
    },
  },
  watch: {},
  methods: {
    // 获取设备列表
    getList(data) {
      if (data) {
        data.deviceTypeId !== undefined && (this.searchMap.deviceTypeId = data.deviceTypeId)
      } else {
        this.activeDevice = ''
      }
      this.loading = true;
      if (!this.searchMap.deptId) {
        this.$message({
          message: "请先选择项目点类型",
          type: "warning",
        });
        return
      }
      if (!this.searchMap.deviceClassifyId) {
        this.$message({
          message: "请先选择设备系统分类",
          type: "warning",
        });
        return
      }
      listDeviceData(this.searchMap).then(res => {
        if (res && 200 === res.code) {
          this.dataList = res.rows;
          this.total = res.total;
        }
        this.loading = false;
      });
    },
    // 获取设备系统分类
    getListDeviceTypesData() {
      listDeviceTypesData({
        pid: 0
      }).then(res => {
        if (res && 200 === res.code) {
          this.deviceClassList = res.data
          if (this.deviceClassList.length) {
            this.searchMap.deviceClassifyId = this.deviceClassList[0].deviceTypeId
            this.searchMap.pageNum = 1;
            this.getDeviceType(this.deviceClassList[0], true)
          }
        }
      })
    },
    // 获取设备类型列表
    getDeviceType(data, isInit) {
      if (this.searchMap.deviceClassifyId === data.deviceTypeId && !isInit) return
      this.searchMap.deviceClassifyId = data.deviceTypeId
      listDeviceTypesData({ pid: data.deviceTypeId }).then(res => {
        if (res && 200 === res.code) {
          this.deviceTypeList = res.data
          this.toGetStatDeviceTypeUnderDeviceNum()
        }
      });
    },
    // 获取设备类型列表数量
    toGetStatDeviceTypeUnderDeviceNum() {
      statDeviceTypeUnderDeviceNum(this.searchMap).then(res => {
        if (res && 200 == res.code) {
          this.$nextTick(() => {
            this.deviceTypeList.map(item => {
              let obj = res.data.filter(item2 => item2.deviceType.deviceTypeId == item.deviceTypeId)[0]
              if (obj) {
                this.$set(item, 'deviceNum', obj.deviceNum)
              }
            })

            this.sum = this.deviceTypeList.filter(item => item.deviceTypeName !== "全部").reduce((total, item) => total + item.deviceNum, 0)
            this.deviceTypeList = [{ deviceTypeName: "全部", deviceNum: this.sum, deviceTypeId: '' }].concat(this.deviceTypeList)
            this.getList();
          })
        }
      })
    },
    // 节点点击触发
    handleNodeClick(data) {
      this.searchMap.deptId = data.id;
      this.searchMap.projectPointName = data.projectPointName
      this.searchMap.projectPointId = data.projectPointId
      this.searchMap.pageNum = 1;
      this.getListDeviceTypesData()
    },
    /** 查询按钮操作 */
    handleSearch() {
      this.searchMap.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    handleReset() {
      this.searchMap.deviceName = ''
      this.searchMap.deviceStatus = ''
      this.searchMap.enableStatus = ''
      this.getList();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deviceId);
      this.multiple = !selection.length;
    },
    // 新增设备
    handleAdd() {
      console.log('新增设备')
      this.titleIndex = "新增设备";
      this.dialogVisible = true;
      for (let p in this.formData) {
        if (p == 'projectPointId') {
          this.formData[p] = this.searchMap.projectPointId
        } else if (p == 'projectPointName') {
          this.formData[p] = this.searchMap.projectPointName
        } else {
          this.formData[p] = ""
        }
      }
      // this.formData = {}
      this.tabActive = 0
      
      // 清空验证
      this.$nextTick(() => {
        let refs = this.$refs.addDeviceForm.$refs
        for(let p in refs){
          let item = refs[p]
          let form = item.$refs.form
          form && form.$refs.formRef.clearValidate()
        }
      })
    },
    // 新增设备因子
    handleAddFactors(row) {
      this.formFactorsData.deviceId = row.deviceId

      this.titleIndexFactors = "新增设备因子";
      this.dialogVisibleFactors = true;
    },
    // 修改数据
    handleEdit(row) {
      // 请求编辑数据后赋值
      this.formData = JSON.parse(JSON.stringify(row));
        console.log("请求编辑数据后赋值 formData XY:", this.formData.positionX, this.formData.positionY)
      // this.formData.projectPointName = this.searchMap.projectPointName
      this.titleIndex = "编辑设备";
      this.dialogVisible = true;
      this.tabActive = 0
    },
    // 删除数据
    handleDelete(row) {
      const ids = row.deviceId || this.ids;
      if (this.$utils.isNotEmpty(ids)) {
        this.$confirm('是否确认删除所选数据项？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          delDeviceData(ids).then(res => {
            if (res && res.code == 200) {
              this.$message.success('删除成功');
              this.getList();
            }
          });
        });
      } else {
        this.$message.warning('请选择数据进行删除');
      }
    },
    // 关联设备
    handleConnect(row) {
      let deviceConnect = this.$refs.deviceConnect
      
      // 设置查询条件
      deviceConnect.searchMap.deptId = this.searchMap.deptId
      deviceConnect.searchMap.deviceClassifyId = this.searchMap.deviceClassifyId
      deviceConnect.formModel.deviceId = row.deviceId
      
      deviceConnect.getListDeviceTypesData(row.deviceClassifyId)
      deviceConnect.getListDeviceCamera(row.deviceId, this.searchMap.deptId)
      deviceConnect.toGetReasonDevice(row.deviceId).then(res => {
        deviceConnect.getListDeviceData(row.deviceId)
      })
      this.dialogVisibleDeviceConnect = true;

    },
    // 一键报修
    handleRepair(row){
      this.dialogRepair = true
      let deviceRepair = this.$refs.deviceRepair

      deviceRepair.formModel = {...deviceRepair.formModel, ...JSON.parse(JSON.stringify(row))};
      deviceRepair.setDictList();
      deviceRepair.toGetDeviceBrand()
    },
    // 添加设备后重新刷新数据
    getData(){
      this.toGetStatDeviceTypeUnderDeviceNum()
      this.getList()
    },
    // 弹窗-设备-新增编辑-取消
    cancel() {
      this.dialogVisible = false;
    },
    // 弹窗-设备关联-取消
    cancelDeviceConnect() {
      this.dialogVisibleDeviceConnect = false;
    },
    // 弹窗-设备因子-新增编辑-取消
    cancelFactors() {
      this.dialogVisibleFactors = false;
    },
    // 弹窗详情-取消
    cancelDetail() {
      // this.dialogVisibleDetail = false;
    },
    // 弹窗详情-取消
    cancelRepair() {
      this.dialogRepair = false;
    },
    // 设备系统类型设置选中项
    setDeviceClassifyActive(id) {
      return id == this.searchMap.deviceClassifyId ? "btn_group_active" : "btn_group"
    },
    // 设备类型设置选中项
    setDeviceTypeActive(id) {
      this.activeDevice = id == this.searchMap.deviceTypeId ? "btn_group_active" : "btn_group"
      return this.activeDevice
    },
    // 设置弹窗tab选中项
    setTabActive(cur) {
      this.tabActive = cur
    },
  },
  components: {
    Aside,
    Breadcrumb,
    ManagementForm,
    FactorsForm,
    DeviceConnect,
    ExportList,
    DeviceRepair
  },
  beforeDestroy() {
    EventBus.$off("currentTree")
  }
};
</script>

<style lang="less">
.serach_item {
  flex-wrap: wrap;
  margin-bottom: 15px;

  button {
    margin-bottom: 15px;
  }
}

.btn_group_active.el-button,
.btn_group.el-button {
  min-width: 100px;
  width: auto;
}

.label-tip {
  margin-right: 15px;
  font-size: 14px;
  line-height: 32px;
  margin-bottom: 15px;
}
</style>
